package org.hako.recite.word.tool;

/**
 * Duplicated kannji detector.
 * 
 * @since 0.4.14
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class DuplicatedKannjiDetector implements KannjiYomiDetector {

	@Override
	public boolean check(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		return rawKannji.indexOf("々") >= 0;
	}

	@Override
	public KannjiYomiDetectResult detect(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		int rawYomiLength = rawYomi.length();
		if (extractResult.getCount() != 2 || rawKannji.length() != 2
				|| rawYomiLength % 2 != 0
				|| !("々".equals(rawKannji.substring(1)))) {
			return new KannjiYomiDetectResult(
					KannjiYomiDetectResult.ERROR_CODE_FAILURE, true);
		}
		KannjiYomiPair pair = new KannjiYomiPair(rawKannji.substring(0, 1),
				rawYomi.substring(0, rawYomiLength / 2));
		return new KannjiYomiDetectResult(pair, generateKannjiWithYomi(
				rawKannji, rawYomi));
	}

	/**
	 * Generate kannji with yomi.
	 * 
	 * @param rawKannji
	 * @param rawYomi
	 * @return
	 */
	private String generateKannjiWithYomi(String rawKannji, String rawYomi) {
		StringBuilder builder = new StringBuilder();
		builder.append(rawKannji.substring(0, 1));
		builder.append('(');
		int rawYomiLength = rawYomi.length();
		builder.append(rawYomi.substring(0, rawYomiLength / 2));
		builder.append(')');
		builder.append(rawKannji.substring(1));
		builder.append('(');
		builder.append(rawYomi.substring(rawYomiLength / 2));
		builder.append(')');
		return builder.toString();
	}
}
